package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Controller
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    /**
     * 处理支付超时订单,下订单15分钟没支付就算超时
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单:{}",new Date());

        //定时到15分钟之前
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        //调用ordermapper查询所有支付超时的订单
        //根据订单状态和下单时间查询超时订单
        List<Orders> timeOutOrderList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);

        //判断结果是否为空,修改订单状态
        if (timeOutOrderList != null && timeOutOrderList.size()>0){
            //不为空就遍历集合修改订单状态
            timeOutOrderList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);//设置取消状态
                orders.setCancelReason("支付超时,自动取消");//取消原因
                orders.setCancelTime(LocalDateTime.now());//取消时间
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 定时处理派送中订单
     */
    @Scheduled(cron = "0 0 1 * * ?")//每晚凌晨1点执行一次
    public void processDeliveryOrder(){
        log.info("处理支付超时订单:{}",new Date());
        //关店时间为12点,所以12点之后,客户没有点确定的订单,把这些配送中的订单改为完成订单
        //查询过去一小时前下的订单,并且状态还未配送中的订单,改为结束状态
        LocalDateTime time = LocalDateTime.now().plusMonths(-60);
        List<Orders> orderList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        //判断
        if (orderList != null & orderList.size()>0){
            //遍历集合添加数据,并调用dao修改订单状态
            orderList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }

    }

}



